package cn.appsys.controller.deve;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.appsys.pojo.AppCategory;
import cn.appsys.pojo.AppInfo;
import cn.appsys.pojo.AppVersion;
import cn.appsys.pojo.DevUser;
import cn.appsys.service.deve.AppCategoryService;
import cn.appsys.service.deve.AppInfoService;
import cn.appsys.service.deve.AppVersionService;
import cn.appsys.service.deve.DicService;
import cn.appsys.tools.Constants;
import cn.appsys.tools.FileSave;
import cn.appsys.tools.Page;

import com.mysql.jdbc.StringUtils;

@Controller
@RequestMapping("sys/deve")
public class DeveController {

	@Resource
	private AppInfoService asi;
	@Resource
	private DicService dsi;
	@Resource
	private AppCategoryService csi;
	@Resource
	private AppVersionService vsi;

	@RequestMapping("main")
	public String toMain() {
		return "developer/main";
	}

	@RequestMapping("logout")
	public String toOut(HttpSession session) {
		if (session.getAttribute(Constants.USER_SESSION2) != null) {
			session.removeAttribute(Constants.USER_SESSION2);
		}
		// 退出到首页
		return "redirect:/index.jsp";
	}

	@RequestMapping(value = "applist", method = RequestMethod.POST)
	public String getAppList(String querySoftwareName, String queryStatus,
			String queryFlatformId, String queryCategoryLevel1,
			String queryCategoryLevel2, String queryCategoryLevel3,
			String pageIndex, Model model) {

		Integer status = null;
		if (queryStatus != null && (!"".equals(queryStatus)))
			status = Integer.parseInt(queryStatus);

		Integer flat = null;
		if (queryFlatformId != null && (!"".equals(queryFlatformId)))
			flat = Integer.parseInt(queryFlatformId);

		Integer l1 = null;
		if (queryCategoryLevel1 != null && (!"".equals(queryCategoryLevel1))) {
			l1 = Integer.parseInt(queryCategoryLevel1);
			model.addAttribute("categoryLevel2List",
					csi.getAppCategoryByparenId(queryCategoryLevel1));
		}

		Integer l2 = null;
		if (queryCategoryLevel2 != null && (!"".equals(queryCategoryLevel2))) {
			l2 = Integer.parseInt(queryCategoryLevel2);
			model.addAttribute("categoryLevel3List",
					csi.getAppCategoryByparenId(queryCategoryLevel2));
		}

		Integer l3 = null;
		if (queryCategoryLevel3 != null && (!"".equals(queryCategoryLevel3))) {
			l3 = Integer.parseInt(queryCategoryLevel3);
		}

		List<AppInfo> appInfoList = asi.getAllBy(querySoftwareName, status,
				flat, l3, l1, l2, Integer.parseInt(pageIndex));
		Page pages = new Page();
		pages.setCurrentPageNo(Integer.parseInt(pageIndex));
		pages.setTotalCount(asi.getAllCount(querySoftwareName, status, flat,
				l3, l1, l2));

		model.addAttribute("statusList", dsi.getStatusList());
		model.addAttribute("flatFormList", dsi.getFlatFormList());
		model.addAttribute("categoryLevel1List",
				csi.getAppCategoryByparenId(null));
		model.addAttribute("appInfoList", appInfoList);

		model.addAttribute("querySoftwareName", querySoftwareName);
		model.addAttribute("queryStatus", queryStatus);
		model.addAttribute("queryFlatformId", queryFlatformId);
		model.addAttribute("queryCategoryLevel1", queryCategoryLevel1);
		model.addAttribute("queryCategoryLevel2", queryCategoryLevel2);
		model.addAttribute("queryCategoryLevel3", queryCategoryLevel3);
		model.addAttribute("pages", pages);
		return "developer/appinfolist";
	}

	@RequestMapping(value = "applist", method = RequestMethod.GET)
	public String toAppList(Model model) {
		List<AppInfo> appInfoList = asi.getAllBy(null, null, null, null, null,
				null, 1);
		Page pages = new Page();
		pages.setTotalCount(asi.getAllCount(null, null, null, null, null, null));

		model.addAttribute("statusList", dsi.getStatusList());
		model.addAttribute("flatFormList", dsi.getFlatFormList());
		model.addAttribute("categoryLevel1List",
				csi.getAppCategoryByparenId(null));
		model.addAttribute("appInfoList", appInfoList);
		model.addAttribute("pages", pages);
		return "developer/appinfolist";
	}

	/**
	 * ajax分类查询
	 * 
	 * @param pid
	 *            父级id
	 * @return
	 */
	@RequestMapping("cateAjax")
	@ResponseBody
	public Object cateAjax(String pid) {
		List<AppCategory> list = new ArrayList<AppCategory>();
		if (pid == "") {
			pid = null;
		}
		list = csi.getAppCategoryByparenId(pid);
		return list;
	}

	/**
	 * ajax访问字典
	 * 
	 * @param type
	 *            类型
	 * @return
	 */
	@RequestMapping("dicAjax")
	@ResponseBody
	public Object dicAjax(String tcode) {
		return dsi.getList(tcode);
	}

	/**
	 * 新增时使用验证名称是否可用
	 * 
	 * @param APKName
	 * @return
	 */
	@RequestMapping("apkexist")
	@ResponseBody
	public Object apkexist(String APKName) {
		HashMap<String, String> hash = new HashMap<String, String>();
		if (StringUtils.isNullOrEmpty(APKName)) {
			hash.put("APKName", "empty");
			return hash;
		}
		int num = asi.getByAPKName(APKName);
		if (num == 0) {
			hash.put("APKName", "noexist");
		} else {
			hash.put("APKName", "exist");
		}
		return hash;
	}
	
	@RequestMapping("delfile")
	@ResponseBody
	public Object delFile(String id,String flag){
		HashMap<String, String> hash = new HashMap<String, String>();
		int num=0;
		
		if(flag.equals("img")){
			num=asi.delFile(id);
		}else if(flag.equals("apk")){
			num=vsi.delFile(id);
		}
		
		if(num>0){
			hash.put("result", "success");
		}else{
			hash.put("result", "failed");
		}
		return hash;
	}
	
	@RequestMapping("appinfoadd")
	public String toAdd() {
		return "developer/appinfoadd";
	}

	@RequestMapping("appinfoaddsave")
	public String saveAdd(AppInfo app, MultipartFile a_logoPicPath,
			HttpServletRequest request) {
		FileSave fs = new FileSave();
		String url = fs.upLoad(a_logoPicPath, request);
		if (url.lastIndexOf(".") != -1) {
			int Id = ((DevUser) request.getSession().getAttribute(
					Constants.USER_SESSION2)).getId();
			app.setDevId(Id);
			app.setCreatedBy(Id);
			app.setCreationDate(new Date());
			app.setLogoPicPath(url.split("[+]")[0]);
			app.setLogoLocPath(url.split("[+]")[1]);
			if (asi.getByAPKName(app.getAPKName()) == 0
					&& asi.addAppInfo(app) > 0) {
				return "redirect:applist";
			}
			return "redirect:appversionadd";
		}
		request.setAttribute("fileUploadError", url);
		return "developer/appinfoadd";
	}

	@RequestMapping("appinfomodify")
	public String tomodify(String id, Model model) {
		model.addAttribute("appInfo", asi.getById(id));
		return "developer/appinfomodify";
	}

	@RequestMapping("appinfomodifysave")
	public String savemodify(AppInfo app, String status,
			HttpServletRequest request, MultipartFile attach) {
		app.setAppInfo(app.getAppInfo().trim());
		if (StringUtils.isNullOrEmpty(status)) {
			app.setStatus(null);
		} else {
			app.setStatus(1);
		}
		
		if (attach != null&&!attach.isEmpty()) {
			FileSave fs = new FileSave();
			String url = fs.upLoad(attach, request);
			if (url.lastIndexOf(".") != -1) {
				app.setLogoPicPath(url.split("[+]")[0]);
				app.setLogoLocPath(url.split("[+]")[1]);
			}else{
				request.setAttribute("fileUploadError", url);
				return "developer/appinfomodify";
			}
		}
		int Id = ((DevUser) request.getSession().getAttribute(
				Constants.USER_SESSION2)).getId();
		app.setUpdateDate(new Date());
		app.setModifyBy(Id);
		app.setModifyDate(new Date());
		if(asi.upAppInfo(app)>0){
			return "redirect:applist";
		}else{
			return "developer/appinfomodify";
		}
		
	}
	
	@RequestMapping("appversionadd")
	public String toVersionadd(String id,Model model){
		List<AppVersion> list=vsi.getAllByAppId(id);
		model.addAttribute("appVersionList",list);
		model.addAttribute("appId", id);
		return "developer/appversionadd";
	}
	
	@RequestMapping("addversionsave")
	public String saveVersionadd(AppVersion av,MultipartFile a_downloadLink,HttpServletRequest request){
		FileSave fs=new FileSave();
		String url=fs.upLoadFile(a_downloadLink, request,62500000, a_downloadLink.getOriginalFilename());
		
		int Id = ((DevUser) request.getSession().getAttribute(
				Constants.USER_SESSION2)).getId();
		av.setCreatedBy(Id);
		av.setCreationDate(new Date());
		av.setDownloadLink(url.split("[+]")[0]);
		av.setApkLocPath(url.split("[+]")[1]);
		av.setApkFileName(a_downloadLink.getOriginalFilename());
		if(vsi.addVersion(av)>0){
			asi.upAppVersion(av.getAppId()+"");
			return "redirect:applist";
		}
		return "developer/appversionadd";
	}
	
	@RequestMapping("appversionmodify")
	public String toVersionModify(String vid,String aid,Model model){
		List<AppVersion> list=vsi.getAllByAppId(aid);
		model.addAttribute("appVersionList",list);
		model.addAttribute("appVersion",vsi.getOneById(vid));
		return "developer/appversionmodify";
	}
	
	@RequestMapping("appversionmodifysave")
	public String saveVersionModify(AppVersion av,HttpServletRequest request,MultipartFile attach){
		FileSave fs=new FileSave();
		String url=fs.upLoadFile(attach, request,62500000, attach.getOriginalFilename());
		int Id = ((DevUser) request.getSession().getAttribute(
				Constants.USER_SESSION2)).getId();
		av.setVersionInfo(av.getVersionInfo().trim());
		av.setModifyDate(new Date());
		av.setModifyBy(Id);
		av.setDownloadLink(url.split("[+]")[0]);
		av.setApkLocPath(url.split("[+]")[1]);
		av.setApkFileName(attach.getOriginalFilename());
		if(vsi.UpAppVersion(av)>0){
			return "redirect:applist";
		}
		return "redirect:error";
	}
	
	@RequestMapping("appview/{id}")
	public String toView(@PathVariable String id,Model mod){
		mod.addAttribute("appInfo",asi.getById(id));
		mod.addAttribute("appVersionList",vsi.getAllByAppId(id));
		return "developer/appinfoview";
	}
	
	@RequestMapping("delapp")
	@ResponseBody
	public Object delApp(String id){
		HashMap<String, String> hash = new HashMap<String, String>();
		vsi.delApp(id);
		int num=asi.delApp(id);
		String result="false";
		if(num>0){
			result="true";
		}else if(num==0){
			result="notexist";
		}
		hash.put("delResult", result);
		return hash;
	}
	
	@RequestMapping("offORno")
	@ResponseBody
	public Object offOrNo(String id){
		HashMap<String, String> hash = new HashMap<String, String>();
		String resultMsg=null;
		AppInfo app=asi.getById(id);
		String flag=null;
		
		if(app.getStatus()==5||app.getStatus()==2){
			flag="上架";
		}else if(app.getStatus()==4){
			flag=null;
		}else if(app.getStatus()==1||app.getStatus()==3){
			hash.put("errorCode", "param000001");
			return hash;
		}else{
			hash.put("errorCode", "exception000001");
			return hash;
		}
		hash.put("errorCode", "0");
		
		int num=asi.upStart(id, flag);
		if(num>0){
			resultMsg="success";
		}else{
			resultMsg="failed";
		}
		hash.put("resultMsg", resultMsg);
		return hash;
	}
}
